const app = getApp();
const common = require('../../utils/common.js');
const api = require('../../config/api.js');

Page({
  data: {
    imgUrl: app.globalData.imgurl,
    parentCategoryList: [],
    categoryList: [],
    keyword: '', 
    parentCategoryName: '',
    parentCategoryImgUrl: '',
		parentCategoryLinkArticleId: null
  },
  onLoad: function (options) {
    this.setData({
      parentCategoryId: options.parentCategoryId
    });
  },
  onShow: function () {
    this.setData({
      keyword: ''
    });
    this.getParentCatagoryList();
    this.getCategoryList();
  },
  getParentCatagoryList: function () {
    let that = this;
    var data = {
      parentCategoryId: that.data.parentCategoryId
    }
    common.request(api.ParentCategoryList, data, 'post').then(function (data) {
      if (data.type === 'success') {
        that.setData({
          parentCategoryList: data.data.parentCategoryList
        });
      } else {
        console.log(data.data.content);
      }
    });
  },
  categorySelect: function (e) {
    const id = e.currentTarget.id;
    console.log(id);
    var newParentCategoryList = this.data.parentCategoryList;
    for (var i = 0; i < newParentCategoryList.length; i++) {
      var parentCategory = newParentCategoryList[i];
      if (parentCategory.id == id) {
        parentCategory.selected = true;
      } else {
        parentCategory.selected = false;
      }
    }
    this.setData({
      parentCategoryId: id,
      parentCategoryList: newParentCategoryList
    })
    this.getCategoryList();
  },
  getCategoryList: function () {
    let that = this;
    var data = {
      parentCategoryId: that.data.parentCategoryId
    }
    common.request(api.CategoryList, data, 'post').then(function (data) {
      if (data.type === 'success') {
        that.setData({
          categoryList: data.data.categoryList,
          parentCategoryName: data.data.parentCategoryName,
          parentCategoryImgUrl: data.data.parentCategoryImgUrl,
					parentCategoryLinkArticleId: data.data.parentCategoryLinkArticleId
        });
      } else {
        console.log(data.data.content);
      }
    });
  },
  toCategory: function (e) {
    var parentCategoryId = this.data.parentCategoryId;
    var categoryId = e.currentTarget.dataset.id;
    //console.log(parentCategoryId,categoryId)
    wx.navigateTo({
      url: '../category/category?parentCategoryId=' + parentCategoryId + '&categoryId=' + categoryId
    })
  },
  keywordInput: function (e) {
    var that = this;
    that.setData({
      keyword: e.detail.value
    });
  },
  onKeywordConfirm: function () {
    var keyword = this.data.keyword;
    wx.navigateTo({
      url: '../category/category?keyword=' + keyword
    })
  },
	link: function () {
		var articleId = this.data.parentCategoryLinkArticleId;
		if (articleId != null && articleId != '') {
			wx.navigateTo({
				url: '/pages/newsDetail/newsDetail?articleId=' + articleId
			})
		}
	}
})